package com.hanserwei.han_picture.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanserwei.han_picture.annotation.AuthCheck;
import com.hanserwei.han_picture.constant.SpaceUserPermissionConstant;
import com.hanserwei.han_picture.constant.UserConstant;
import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.domain.common.DeleteRequest;
import com.hanserwei.han_picture.domain.entity.po.Picture;
import com.hanserwei.han_picture.domain.entity.po.User;
import com.hanserwei.han_picture.domain.entity.vo.*;
import com.hanserwei.han_picture.domain.request.picture.*;
import com.hanserwei.han_picture.enums.ImageCategory;
import com.hanserwei.han_picture.enums.ResponseCodeEnum;
import com.hanserwei.han_picture.manager.RedisManager;
import com.hanserwei.han_picture.manager.auth.annotation.SaSpaceCheckPermission;
import com.hanserwei.han_picture.service.seviceImpl.PictureServiceImpl;
import com.hanserwei.han_picture.service.seviceImpl.UserServiceImpl;
import com.hanserwei.han_picture.utils.ThrowUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 图片(picture)表控制层
 *
 * @author hanserwei
 */
@RestController
@RequestMapping("/picture")
@RequiredArgsConstructor
@Tag(name = "ImageController")
public class PictureController {

    private final PictureServiceImpl pictureServiceImpl;

    private final UserServiceImpl userServiceImpl;

    private final RedisManager redisManager;


    @Operation(summary = "上传图片")
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public ApiResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                PictureUploadRequest pictureUploadRequest,
                                                HttpServletRequest request
    ) {
        ThrowUtils.throwIf(ObjUtil.isNull(multipartFile), ResponseCodeEnum.INVALID_PARAMETER, "图片为空！");
        User loginUser = userServiceImpl.getLoginUser(request);
        PictureVO pictureVO = pictureServiceImpl.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ApiResponse.success("上传成功！", pictureVO);
    }

    @Operation(summary = "Url上传图片")
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public ApiResponse<PictureVO> uploadPictureByURL(@RequestBody PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtil.isEmpty(pictureUploadRequest), ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        String url = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureServiceImpl.uploadPicture(url, pictureUploadRequest, loginUser);
        return ApiResponse.success("上传成功！", pictureVO);
    }

    @Operation(summary = "删除图片")
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public ApiResponse<Boolean> deletePictureById(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        boolean result = pictureServiceImpl.deletePicture(deleteRequest.getId(), loginUser);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "删除失败！");
        return ApiResponse.success("删除成功！", true);
    }

    @Operation(summary = "更新图片(管理员）")
    @PostMapping("/update")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUpdateRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        boolean result = pictureServiceImpl.updatePicture(pictureUpdateRequest, loginUser);
        return ApiResponse.success("更新成功！", result);
    }

    @Operation(summary = "分页获取图片列表（管理员）")
    @PostMapping("/list/page")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        Page<Picture> page = pictureServiceImpl.listPictureByPage(pictureQueryRequest);
        return ApiResponse.success("获取成功！", page);
    }

    @Operation(summary = "分页获取图片列表（用户）")
    @PostMapping("/list/page/vo")
    public ApiResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(pictureQueryRequest.getPageSize() > 20, ResponseCodeEnum.INVALID_PARAMETER, "你不能一次查这么多！");
        Page<PictureVO> page = pictureServiceImpl.getPictureVOPage(pictureServiceImpl.listPictureByPage(pictureQueryRequest));
        return ApiResponse.success("获取成功！", page);
    }

    @Operation(summary = "根据图片Id搜索图片（管理员）")
    @GetMapping("/get")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<Picture> getPictureById(@RequestParam("id") Long id) {
        ThrowUtils.throwIf(id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        return ApiResponse.success("查询成功！", pictureServiceImpl.getPictureById(id));
    }

    @Operation(summary = "根据图片Id搜索图片（用户）")
    @GetMapping("/get/vo")
    public ApiResponse<PictureVO> getPictureVOById(@RequestParam("id") Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        return ApiResponse.success("查询成功！", pictureServiceImpl.getPictureVOById(id, loginUser));
    }

    @Operation(summary = "编辑图片")
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public ApiResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        boolean result = pictureServiceImpl.editPicture(pictureEditRequest, loginUser);
        return ApiResponse.success("编辑成功！", result);
    }

    @Operation(summary = "获取图片标签和分类")
    @GetMapping("/tag_category")
    public ApiResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();

        // 从Redis获取前10个热门标签
        List<String> hotTags = redisManager.getTopTags(10);
        // 如果Redis中没有标签，使用默认标签
        if (hotTags.isEmpty()) {
            hotTags = Arrays.asList("热门", "搞笑", "生活", "艺术", "校园", "背景", "创意", "游戏", "动漫", "其他");
        }

        // 获取所有图片分类
        List<String> categoryList = Arrays.stream(ImageCategory.values())
                .map(ImageCategory::getChineseName)
                .toList();

        pictureTagCategory.setTagList(hotTags);
        pictureTagCategory.setCategoryList(categoryList);
        return ApiResponse.success("获取成功！", pictureTagCategory);
    }

    @Operation(summary = "图片审核")
    @PostMapping("/review")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<Boolean> dePictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        return ApiResponse.success("审核成功！", pictureServiceImpl.dePictureReview(pictureReviewRequest, loginUser));
    }

    @Operation(summary = "批量上传图片")
    @PostMapping("/batch/upload")
    public ApiResponse<PictureBatchUploadVO> batchUploadPictures(
            @RequestPart("files") MultipartFile[] files,
            PictureBatchUploadRequest batchUploadRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(files == null || files.length == 0, ResponseCodeEnum.INVALID_PARAMETER, "上传文件不能为空");
        User loginUser = userServiceImpl.getLoginUser(request);
        PictureBatchUploadVO result = pictureServiceImpl.batchUploadPictures(files, batchUploadRequest, loginUser);
        return ApiResponse.success("批量上传完成！", result);
    }

    @PostMapping("/search/color")
    @Operation(summary = "根据颜色搜索图片")
    @Deprecated(since = "不打算使用！")
    public ApiResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest colorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(colorRequest == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        String picColor = colorRequest.getPicColor();
        Long spaceId = colorRequest.getSpaceId();
        User loginUser = userServiceImpl.getLoginUser(request);
        List<PictureVO> pictureVOList = pictureServiceImpl.searchPictureByColor(spaceId, picColor, loginUser);
        return ApiResponse.success(pictureVOList);
    }

    /**
     * 图片批量操作
     *
     * @param batchRequest 图片批量操作请求
     * @param request      当前登录用户
     * @return 图片批量操作结果
     */
    @PostMapping("/edit/batch")
    @Operation(summary = "图片批量操作,仅个人空间可用")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public ApiResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest batchRequest, HttpServletRequest request) {
        User loginUser = userServiceImpl.getLoginUser(request);
        boolean result = pictureServiceImpl.editPictureByBatch(batchRequest, loginUser);
        return ApiResponse.success(result);
    }

    @GetMapping("/review/count")
    @Operation(summary = "获取图片审核情况")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<PictureReviewCountVO> getPictureReviewCount() {
        return ApiResponse.success("获取成功！", pictureServiceImpl.getPictureReviewCount());
    }

    @Operation(summary = "获取空间图片的标签与分类")
    @GetMapping("/tag_category/space")
    public ApiResponse<PictureTagCategory> listPictureTagCategoryBySpaceId(@RequestParam("spaceId") Long spaceId, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceId <= 0, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        User loginUser = userServiceImpl.getLoginUser(request);
        PictureTagCategory pictureTagCategory = pictureServiceImpl.listPictureTagAndCategoryBySpaceId(spaceId, loginUser);
        return ApiResponse.success("获取成功！", pictureTagCategory);

    }

    @Operation(summary = "使用AI重绘图片风格")
    @PostMapping("/style_regen")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public ApiResponse<PictureStyleRegenVO> generateImage(@RequestBody PictureStyleRegenRequest request, HttpServletRequest httpServletRequest) {
        User loginUser = userServiceImpl.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(loginUser == null, ResponseCodeEnum.UNAUTHORIZED, "请先登录！");
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        PictureStyleRegenVO result = pictureServiceImpl.generateImage(request);
        return ApiResponse.success("生成成功！", result);
    }

    @Operation(summary = "查询重绘任务结果")
    @GetMapping("/style_regen/task")
    public ApiResponse<PictureStyleRegenTaskVO> queryTaskStatus(@RequestParam("taskId") String taskId, HttpServletRequest request) {
        User loginUser = userServiceImpl.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ResponseCodeEnum.UNAUTHORIZED, "请先登录！");
        ThrowUtils.throwIf(taskId == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        PictureStyleRegenTaskVO result = pictureServiceImpl.queryTaskStatus(taskId);
        return ApiResponse.success("查询成功！", result);
    }

}
